class Router {
	constructor() {
		this.routes = {};
		this.beforeEachHooks = [];
		this.withRoutes = ['/', '/uni_modules/sxran-im-modules/pages/login/login'];
		this.currentPath = this.getCurrentPath(); // 初始化为当前路径
		this.setupEventListeners(); // 设置事件监听器
	}

	// 获取当前路径
	getCurrentPath() {
		if (typeof window !== 'undefined' && window.location) {
			return window.location.hash.slice(1) || '/';
		} else if (typeof uni !== 'undefined') {
			const pages = getCurrentPages();
			if (pages.length > 0) {
				const currentPage = pages[pages.length - 1];
				return currentPage.route;
			}
		}
		return '/';
	}

	// 设置事件监听器
	setupEventListeners() {
		if (typeof window !== 'undefined' && window.addEventListener) {
			window.addEventListener('popstate', this.handleHashChange.bind(this));
		}
		if (typeof uni !== 'undefined') {
			// 监听 UniApp 的路由事件
			uni.addInterceptor('navigateTo', {
				invoke: this.interceptNavigateTo.bind(this)
			});
			uni.addInterceptor('redirectTo', {
				invoke: this.interceptRedirectTo.bind(this)
			});
			uni.addInterceptor('switchTab', {
				invoke: this.interceptSwitchTab.bind(this)
			});
			uni.addInterceptor('navigateBack', {
				invoke: this.interceptNavigateBack.bind(this)
			});
		}
	}

	// 添加路由
	addRoute(path, callback) {
		this.routes[path] = callback;
	}

	// 添加路由守卫
	beforeEach(guard) {
		this.beforeEachHooks.push(guard);
		// 如果已经初始化了路由，立即执行一次守卫
		if (this.currentPath !== undefined) {
			const to = {
				path: this.currentPath
			};
			const from = {
				path: this.currentPath
			};
			const next = (flag) => {
				console.log('beforeEach', flag);
				const route = this.routes[this.currentPath] || this.addDefaultRoute(this.currentPath);
				route();
				return flag;
			};
			let flag = true;

			for (const hook of this.beforeEachHooks) {
				const result = hook(to, from, next);
				if (result === false) {
					flag = false;
					break;
				}
			}

			next(flag);
		}
	}

	// 处理 hash 变化
	handleHashChange() {
		const path = window.location.hash.slice(1) || '/';
		const flag = this.processRoute(path);
		if (flag === false) {
			// 如果返回 false，取消导航
			window.history.replaceState(null, '', `#${this.currentPath}`);
		}
	}

	// 处理路由
	processRoute(path) {
		let route = this.routes[path];

		if (!route) {
			// 如果当前路由不存在，自动添加一个默认的路由处理函数
			console.warn(`Route ${path} not found. Adding a default route.`);
			route = this.addDefaultRoute(path);
		}

		// 执行所有 before each 钩子
		const to = {
			path
		};
		const from = {
			path: this.currentPath
		};
		let flag = true;

		for (const hook of this.beforeEachHooks) {
			const next = (result) => {
				if (result === false) {
					flag = false;
				}
			};
			hook(to, from, next);
			if (flag === false) {
				break;
			}
		}

		if (flag !== false) {
			route();
			this.currentPath = path;
		}

		return flag;
	}

	// 添加默认路由
	addDefaultRoute(path) {
		const defaultCallback = () => {
			console.log(`Default route for ${path}`);
		};
		this.routes[path] = defaultCallback;
		return defaultCallback;
	}

	// 拦截 navigateTo
	interceptNavigateTo(args) {
		const path = args.url.split('?')[0];
		return this.processRoute(path);

	}

	// 拦截 redirectTo
	interceptRedirectTo(args) {
		const path = args.url.split('?')[0];
		return this.processRoute(path);

	}

	// 拦截 switchTab
	interceptSwitchTab(args) {
		const path = args.url.split('?')[0];
		return this.processRoute(path);

	}

	// 拦截 navigateBack
	interceptNavigateBack(args) {
		// navigateBack 不会改变当前路径，只需处理返回逻辑
		// 这里可以添加返回逻辑，例如记录历史路径等
		console.log('Navigating back');
		return this.processRoute(path);
	}
	
	setWithRoutes(path){
		//如果是数组需要合并
		if(!path || (Array.isArray(path) && path.length == 0)) {
			this.withRoutes = [];
			return;
		}
		if(Array.isArray(path)){
			this.withRoutes = path;
		}else{
			this.withRoutes.push(path);
		}
	}
	
	getWithRoutes(){
		return this.withRoutes;
	}
}

export default new Router();